package com.dawn.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dawn.common.lang.Result;
import com.dawn.entity.Blog;
import com.dawn.service.BlogService;
import com.dawn.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.java2d.loops.Blit;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dawnfades
 * @since 2021-05-14
 */
@RestController
public class BlogController {

    @Autowired
    BlogService blogService;

    @GetMapping("/blog")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){
//        每一页多少条记录
        Page page = new Page(currentPage,5);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));

        return Result.success(pageData);
    }

    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id")Long id){
        Blog blog = blogService.getById(id);
        Assert.notNull(blog,"该博客已被删除");
        return Result.success(blog);
    }

    @RequiresAuthentication//需要认证才能访问
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog){
        Blog temp = null;
//        没有id为编辑状态，否则为添加
        if(blog.getId() != null){
            temp = blogService.getById(blog.getId());
            //只能编辑自己的文章
            Assert.isTrue(temp.getId()== ShiroUtil.getprofile().getId(),"没有权限编辑");
        }else {
            //添加博客
            temp = new Blog();
            temp.setUserId(ShiroUtil.getprofile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }

        BeanUtil.copyProperties(blog,temp,"id","userId","created","status");
        blogService.saveOrUpdate(temp);
        return Result.success(null);
    }

}
